import {
  KeyWordModel
} from '../../models/keyword'
import {
  BookModel
} from '../../models/book'
import { paginationBev } from '../behaviors/pagination'
let keyWordModel = new KeyWordModel();
let bookModel = new BookModel();
// components/search/index.js
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    searchInputValue: '',
    loading: false, // loading + 请求锁
    loadingCenter: false
  },

  // 初始化组件调用的生命周期
  attached() {
    const historyWords = keyWordModel.getHistory();
    const hotWords = keyWordModel.getHot();
    hotWords.then(res => {
      const { hot: hotWords} = res;
      this.setData({
        hotWords
      })
    })
    this.setData({
      historyWords
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore() {
      if(!this.data.searchInputValue) {
        return;
      }
      if(this.isLocked()) {
        return;
      }
      // 会存在多次请求相同的情况 加 loading锁
      if(this.hasMore()) {
        this.locked();
        bookModel.search(this.getCurrentStart(), this.data.searchInputValue)
            .then(res => {
              const { books: newBookData } = res;
              this.setMoreData(newBookData);
              this.unLocked();
            }, () => {
              this.unLocked();
            })
      }
    },
    onCancel(event) {
        // 调用前先清空
        this.initialize();
      this.triggerEvent('cancel', {}, {});
    },
    onConfirm(event) {
      this._showResult();
      this._showLoadingCenter();
      // 调用前先清空
      this.initialize();
      const q = event.detail.value || event.detail.text;
      bookModel.search(0, q)
          .then(res => {
            const { books, total } = res;
            this.setMoreData(books); // 行为func
            this.setTotal(total); // 行为func
            this.setData({
              searchInputValue: q
            });
            keyWordModel.addToHistory(q);
            this._hideLoadingCenter();
          })
    },
    onDelete() {
        // 调用前先清空
        this.initialize();
        this._closeResult();
    },
    _showResult() {
      this.setData({
        searching: true
      });
    },
    _closeResult() {
      this.setData({
        searching: false,
        searchInputValue: ''
      });
    },
    _showLoadingCenter() {
        this.setData({
            loadingCenter: true
        })
    },
    _hideLoadingCenter() {
        this.setData({
            loadingCenter: false
        })
    }
  }
})
